package com.shardingsphereproxy.springbootshardingsphereproxy.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

@Configuration
@PropertySource("classpath:jedis.properties")
public class JedisUtil3 {
    @Value("${host}")
    private String host;

    @Value("${password}")
    private String password;


    @Value("${port}")
    private String port;

    @Value("${maxIdle}")
    private String maxIdle;

    @Value("${maxTotal}")
    private String maxTotal;

    @Value("${timeout}")
    private Integer timeout;


    private static JedisPool jedisPool = null;

    @PostConstruct
    private void jedisInit() {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        // 最大空闲数
        jedisPoolConfig.setMaxIdle(Integer.valueOf(maxIdle));
        // 最大连接数
        jedisPoolConfig.setMaxTotal(Integer.valueOf(maxTotal));
        jedisPool = new JedisPool(jedisPoolConfig, host, Integer.valueOf(port),timeout,password);

    }
    @PreDestroy
    private void destroy(){
        jedisPool.close();
    }

    /**
     * 获得Jedis
     *
     * @return
     */
    public static Jedis getJedis() {
        return jedisPool.getResource();
    }

    /**
     * 释放资源
     *
     * @param jedis
     */
    public static void closeJedis(Jedis jedis) {
        jedis.close();
    }

    public static String getCommonId() {
        Jedis jedis = getJedis();
        String id = "id";
        Long incr = jedis.incr(id);
        if (incr == 1) {
            jedis.expire(id, 24 * 3600 - LocalTime.now().toSecondOfDay());

        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        Long time = Long.valueOf(LocalDate.now().format(formatter));
        closeJedis(jedis);
        String commonId = "" + time + incr;
        return commonId;
    }

    public static String getOrderId() {
        Jedis jedis = getJedis();
        String id = "order_id";
        Long incr = jedis.incr(id);
        if (incr == 1) {
            jedis.expire(id, 24 * 3600 - LocalTime.now().toSecondOfDay());

        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        String time = LocalDate.now().format(formatter);
        closeJedis(jedis);
        return "ORDER_ID_" + time + "_" + incr;
    }
}


